﻿using System;
using System.IO;
using HAVNet.Core.LitJson;

namespace pmf
{
    class ConfigManager
    {
        public static bool cargarConfiguracion<T>(ref T conf, string fileName)
            where T : new()
        {
            if (readConfig<T>(ref conf, fileName))
                return true;
            createConfig<T>(fileName);
            return readConfig<T>(ref conf, fileName);
        }

        public static bool readConfig<T>(ref T conf, string fileName)
        {
            try {
                conf = JsonMapper.ToObject<T>(File.ReadAllText(fileName));
                return true;
            } catch {
                return false;
            }
        }

        public static bool createConfig<T>(string fileName) 
            where T : new()
        {
            try {
                T t = new T();
                saveConfig<T>(t, fileName);
                return true;
            } catch {
                return false;
            }
        }

        public static bool saveConfig<T>(T conf, string fileName)
        {
            try {
                using (TextWriter textWriter = File.CreateText(fileName)) {
                    JsonWriter jw = new JsonWriter(textWriter);
                    jw.NewLineStyle = NewLineStyleEnum.RN;
                    jw.PrettyPrint = true;
                    JsonMapper.ToJson(conf, jw);
                    textWriter.Close();
                }
                return true;
            } catch (Exception exx) {
                Logger.general.loguear(exx);
                return false;
            }
        }
    }
}
